package com.yixing.tech.common.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.StringJoiner;


/**
 * @author yixing tech
 */
@Component
public class SequenceUtil {

    private static final int DEFAULT_LENGTH = 3;

    private static SequenceUtil self;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    private void init(){
        self = this;
    }

    /**
     * id 自增
     *
     * @return
     */
    public static String getSequence(Object prefix) {
        String currentDate = DateUtil.getDateStr(new SimpleDateFormat(
                "yyMMdd"));
        if (null == prefix) prefix = "";
        String keyStr = prefix + currentDate;
        String key = RedisGroupName.ID + keyStr;
        long seq = incr(key);
        String str = String.valueOf(seq);
        int len = str.length();
        if (len < DEFAULT_LENGTH) {
            int rest = DEFAULT_LENGTH - len;
            StringJoiner stringJoiner = new StringJoiner("");
            for (int i = 0; i < rest; i++) {
                stringJoiner.add("0");
            }
            stringJoiner.add(str);
            str = stringJoiner.toString();
        }
        StringJoiner sj = new StringJoiner("");
        sj.add(keyStr).add(str);
        return sj.toString();
    }


    /**
     * 获取递增
     *
     * @param key
     * @return
     */
    public static long incr(String key) {
        return self.stringRedisTemplate.opsForValue().increment(key);
    }
}

